<template>
	<div class="app-container">
		<div class="bgWhite radius8" v-if="showFilter == false">
			<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
				<el-tab-pane label="我的客户" name="1"></el-tab-pane>
				<el-tab-pane label="重点客户" name="2"></el-tab-pane>
				<el-tab-pane label="全部客户" name=""></el-tab-pane>
			</el-tabs>
			<el-form class="p20 flex col-top row-between" :model="queryParams" label-width="80px" ref="queryRef"
				:inline="true">
				<div>
					<el-form-item label="关键词" prop="keyWords">
						<el-input v-model="queryParams.keyWords" placeholder="不限" clearable class="resetInput"
							style="width: 200px" :suffix-icon="Search" @keyup.enter="handleQuery" />
					</el-form-item>
					<el-form-item label="客户状态" prop="customerStatus">
						<el-select v-model="queryParams.customerStatus" placeholder="客户状态" size="large"
							style="width: 200px">
							<el-option v-for="dict in bus_customer_status" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="客户类型" prop="customerType">
						<el-select v-model="queryParams.customerType" placeholder="客户类型" size="large"
							style="width: 200px">
							<el-option v-for="dict in bus_customer_type" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="客户星级" prop="customerStarLevel">
						<el-select v-model="queryParams.customerStarLevel" placeholder="客户星级" size="large"
							style="width: 200px">
							<el-option v-for="dict in bus_customer_starlevel" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="客户来源" prop="opportunitySource">
						<el-select v-model="queryParams.opportunitySource" placeholder="客户来源" size="large"
							style="width: 200px">
							<el-option v-for="dict in bus_source" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="时间筛选" prop="createTimes">
						<datePickerRange ref="clearPicker" @dateRangeValue="changeTime"></datePickerRange>	
					</el-form-item>
					
				</div>
				<div class="flex col-center row-end" style="width: 516px;margin-right: 0;">
					<div class="main-color cursor mr5" style="width: 40px;line-height: 18px;"
						@click="showFilter = true">高级筛选</div>
					<el-button class="searchBtn" type="defaultBtn" @click="handleQuery">查询</el-button>
					<el-button class="searchBtn" icon="Refresh" @click="resetQuery">重置</el-button>
				</div>
			</el-form>
		</div>
		<!-- 高级筛选 -->
		<filterItem v-if="showFilter == true" 
		@queryParamsFunc="queryParamsFunc" @back="showFilter = false"
		:queryParamsProp="queryParams" :propBus="propBus" :teamOptions="teamOptions"
		:activeName="activeName"
		></filterItem>
		<div class="bgWhite radius8 p20 mt25">
			<div class="flex col-center row-between mb20">
				<span class="fb fs16">客户列表</span>
				<div>
					<el-button type="defaultBtn" icon="plus" v-hasPermi="['customer:add']" @click="handleAdd">添加</el-button>
					<el-button type="operate" v-hasPermi="['customer:importData']"  @click="importCustomer()">导入客户</el-button>
					<el-button type="operate" v-hasPermi="['customer:transferCustomer']" @click="transCustomer()">转移客户</el-button>
					<el-button type="operate" v-hasPermi="['customer:transferHighSeas']" @click="handleRemove()">移入公海</el-button>
				</div>
			</div>
			<el-table v-loading="loading" :data="list" style="width: 100%;"
				:header-row-style="{background:'#FAFAFA',color:'#0C1019',height:'54px'}" :cell-style="{height:'54px'}"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="客户姓名" align="center">
					<template #default="scope">
						<span class="main-color cursor"
							@click="handleDetail('/peoples/customer/portrait/user/' + scope.row.id)">{{scope.row.customerName}}</span>
					</template>
				</el-table-column>
				<el-table-column label="客户状态" align="center">
					<template v-slot="scope">
						<div class="flex col-center row-center" :class="activeStatus(scope.row.customerStatus)">
							<span class="drop"></span>
							<dict-tag :options="bus_customer_status" :value="scope.row.customerStatus" />
						</div>
					</template>
				</el-table-column>
				<el-table-column label="客户星级" align="center" prop="userName">
					<template #default="scope">
						<el-rate v-model="scope.row.customerStarLevel" disabled text-color="#ff9900" />
					</template>
				</el-table-column>
				<el-table-column label="创建人" align="center" prop="createByName" :show-overflow-tooltip="true" />
				<el-table-column label="业务经理" align="center" prop="businessManagerName" :show-overflow-tooltip="true" />
				<el-table-column label="手机号码" align="center" prop="phoneNumber" :show-overflow-tooltip="true" />
				<el-table-column label="订单总数" align="center" prop="orderCount">
					<template #default="scope">
						{{scope.row.orderCount || 0}}
					</template>
				</el-table-column>
				<el-table-column label="订单金额" align="center" prop="orderTotalAmount" >
					<template #default="scope">
						￥{{scope.row.orderTotalAmount || 0}}
					</template>
				</el-table-column>
				<el-table-column label="最后跟进" align="center" prop="latestFollowupTime" :show-overflow-tooltip="true" />
				<el-table-column label="未跟进天数" align="center" prop="notFollowingDay" :show-overflow-tooltip="true" />
				<el-table-column label="创建时间" align="center" prop="createTime"/>
				<el-table-column fixed="right" label="操作" align="center" width="300px"
					class-name="small-padding fixed-width">
					<template #default="scope">
						<el-button link class="linkBtnColor" type="primary"
						 v-hasPermi="['followup_record:add']"
							@click="handleUser(scope.row)">跟进</el-button>
						<el-button link class="linkBtnColor" type="primary"
						 v-hasPermi="['customer:edit']"
							@click="handleEdit(scope.row)">编辑</el-button>
						<el-button link class="linkBtnColor" type="primary"
							v-hasPermi="['customer:editTopUp']" @click="handleEditTopUp(scope.row)">
							{{!scope.row.topUpTime ? '置顶' : '取消置顶'}}
						</el-button>
						<el-button link class="linkBtnColor" type="primary" 
						v-hasPermi="['customer:addOrder']"
							@click="handleOrder(scope.row)">新建订单</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
				v-model:limit="queryParams.pageSize" @pagination="getList" />
		</div>
		<!-- 转移客户 -->
		<el-dialog v-model="dialogFormVisible" width="460" title="转移客户" center :align-center="true"
			custom-class="radius8">
			<el-form :model="form" ref="formRef" :rules="rules" label-width="95px">
				<el-form-item label="业务经理：" prop="businessManagerId">
					<el-select v-model="form.businessManagerId" filterable size="large" placeholder="请选择"
						style="width: 318px">
						<el-option v-for="dict in businessList" :key="dict.userId" :label="dict.userName"
							:value="dict.userId" />
					</el-select>
				</el-form-item>
				<el-form-item label="备注信息：" prop="remark">
					<div class="radius8" style="padding:5px;background-color:#F7F8FA ;">
						<el-input v-model="form.remark" style="width: 308px;box-shadow: none;" :rows="6" type="textarea"
							placeholder="请输入备注信息" resize="none"
							:input-style="{background:'#F7F8FA',borderRaduis:'5px',boxShadow:'none'}" />
					</div>
					<div class="color-red fs14">*如需变更客户相关记录业务经理员请勾选相关选项</div>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer text-right" style="padding-top: 0;">
					<el-button plain @click="dialogFormVisible = false">取消</el-button>
					<el-button type="defaultBtn" @click="submitForm">确定</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 批量导入客户 -->
		<el-dialog title="批量导入" center v-model="upload.open" width="694px" append-to-body>
			<el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
				:action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
				:on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
				<div>
					<div class="flex col-top">
						<img src="@/assets/images/Img.png" width="80" height="80" alt="" />
						<div class="text-left ml15 mt5" style="text-align: left;">
							<span class="fb color333 mr5 mt5">上传导入客户文件</span>
							<el-link type="primary" :underline="false"
								style="font-size:12px;vertical-align: baseline;border: 1px solid #4DACB1;background: #EDF6F7;border-radius: 2px;line-height: 22px;padding: 0 4px;"
								@click.stop="importTemplate">下载模板</el-link>
							<div class="fs12 mt6 mb8">
								<span>文件后缀名必须为xls 或xlsx（即Excel格式），文件大小不得大于10M，最多支持导入3000条数据</span>
							</div>
							<div class="main-color fs12">上传文件</div>
						</div>
					</div>
				</div>
			</el-upload>
			<template #footer>
				<div class="dialog-footer text-right">
					<el-button class="cancelSubBtn" @click="upload.open = false">取 消</el-button>
					<el-button type="primary" @click="submitFileForm" class="mainSubBtn">确 定</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 添加计划 -->
		<addDialog ref="dialog2" :customerId="customerId" @recordList=""></addDialog>
		<!-- 新增客户弹窗 -->
		<operateCustomer ref="customerPop" @refreshList="getList"></operateCustomer>
		<!-- //新建订单弹窗 -->
		<operateOrder ref="addOrder" @refreshList="getList" :addOrderCustomerMes="addOrderCustomerMes"></operateOrder>
	</div>
</template>

<script>
	import {
		resetForm,
		getUserInfo
	} from '@/utils/ruoyi'
	import {
		customerList,
		favoriteCustomerList,
		invalidTransferCustomer,
		listData,
		transferCustomer,
		transferHighSeas,//移入公海
		editTopUp,//置顶
		editUnTopUp//取消置顶
	} from "@/api/business/customer";
	import filterItem from '@/components/filterItem/index.vue'
	import {
		Search
	} from '@element-plus/icons-vue'
	import {
		useRouter
	} from 'vue-router'
	import {
		getUserListData
	} from "@/api/business/teamOpportunity";
	import {
		getToken
	} from "@/utils/auth";
	import operateCustomer from './components/operateCustomer.vue' //新增/编辑客户
	import operateOrder from '@/views/business/order/components/operateBox.vue' //新建订单弹窗
	import addDialog from '../components/checkIn.vue' //添加跟进
	export default {
		components: {
			operateCustomer,
			operateOrder,
			filterItem,
			addDialog
		},
		data() {
			return {
				bus_customer_status: this.useDict('bus_customer_status').bus_customer_status,
				bus_channel: this.useDict('bus_channel').bus_channel,
				bus_customer_type: this.useDict('bus_customer_type').bus_customer_type,
				bus_customer_starlevel: this.useDict('bus_customer_starlevel').bus_customer_starlevel,
				bus_client_tag: this.useDict('bus_client_tag').bus_client_tag,
				bus_source:this.useDict('bus_source').bus_source,//客户来源
				propBus: {},
				activeName: '1',
				showFilter: false, //高级筛选
				index: 0, //0我的客户 1重点客户
				total: '',
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					customerStatus: '', //客户状态
					customerType: '', //客户类型
					customerStarLevel: '', //客户星级
					startTime: '', //开始时间
					endTime: '', //结束时间					
					keyWords: '', //关键词
					customerRoleType: 1, //1=我的客户 2=下属客户 3重点客户 4今日新增
					recentlyConsumption: '', //最近消费1=一周内2=二周内3=一月内
					recentlyConsumptionNumber: '', //最近消费次数1=1次2=2次3=3次4=4次5=5次6=5次以上
					followUpStartTime: '', //下次跟进开始时间
					followUpEndTime: '', //下次跟进结束时间
					customerLabels: '', //客户标签
					businessManagerId: '', //业务经理
					createTimes: '',
					opportunitySource:'',//客户来源
				},
				list: [],
				loading: true,
				ids: [], //复选框选中的id
				dialogFormVisible: false, //转移客户弹窗
				rules: {
					businessManagerId: [{
						required: true,
						message: '请选择业务经理',
						trigger: 'blur'
					}, ]
				},
				form: {
					businessManagerId: '',
					remark: ''
				},
				isAllUser: false, //不是主管
				teamOptions: [],
				deptId: '',
				upload: {
					// 是否显示弹出层（用户导入）
					open: false,
					// 弹出层标题（用户导入）
					title: "",
					// 是否禁用上传
					isUploading: false,
					// 是否更新已经存在的用户数据
					updateSupport: 0,
					// 设置上传的请求头部
					headers: {
						Authorization: "Bearer " + getToken()
					},
					// 上传的地址
					url: import.meta.env.VITE_APP_BASE_API + '/customer/importData',
				},
				addOrderCustomerMes: {}, //要创建订的客户信息
				customerId:'',//要跟进的客户id
			}
		},
		created() {
			this.propBus = {
				bus_client_tag: this.bus_client_tag,
				bus_customer_status: this.bus_customer_status,
				bus_customer_type: this.bus_customer_type,
				bus_customer_starlevel: this.bus_customer_starlevel
			}
			this.getList();
			this.handleCustomer()
			this.getUserList()
			// console.log(this.getUserInfo,'getUserInfo')
		},
		methods: {
			/** 下载模板操作 */
			importTemplate() {
				this.download("/customer/templateDownload", {}, `customer_template${new Date().getTime()}.xlsx`);
			},
			//导入
			importCustomer() {
				this.importType = 0
				this.upload.open = true
			},
			/**文件上传中处理 */
			handleFileUploadProgress(event, file, fileList) {
				this.upload.isUploading = true;
			},
			/** 文件上传成功处理 */
			handleFileSuccess(response, file, fileList) {
				this.upload.open = false;
				this.upload.isUploading = false;
				this.$refs["uploadRef"].handleRemove(file);
				this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
					response.msg + "</div>", "导入结果", {
						dangerouslyUseHTMLString: true
					});
				this.getList();
			},
			submitFileForm() {
				this.$refs["uploadRef"].submit();
			},
			// 置顶
			handleEditTopUp(row) {
				if(!row.topUpTime){
					editTopUp(row.id).then(res => {
						this.$modal.msgSuccess("已置顶");
						this.getList();
					})
				}else{
					editUnTopUp(row.id).then(res => {
						this.$modal.msgSuccess("已取消置顶");
						this.getList();
					})
				}
			},
			// 移入公海
			handleRemove() {
				if (this.ids.length == 0) {
					this.$message.error('请先选择用户');
					return false;
				}
				let arr = {
					ids: this.ids,
					remark:''
				}
				this.$confirm(this.isAllUser == false ? '确认要移入公司公海吗？' : '确认要移入部门公海吗？', '提示')
					.then(_ => {
						this.transferHighSeas(arr)
						done();
					})
					.catch(_ => {});
			},
			transferHighSeas(arr) {
				transferHighSeas(arr).then(res => {
					this.$modal.msgSuccess("移入公海成功");
					this.getList();
				})
			},
			handleCustomer() {
				listData({
					deptId: this.deptId
				}).then(response => {
					this.businessList = response.data
				});
			},
			/**
			 * 获取本人和下级用户数据
			 */
			getUserList() {
				let userInfo = this.getUserInfo();
				if (userInfo.roles != null) {
					for (var key of userInfo.roles) {
						if (key.roleKey == 'manager' || key.roleKey == 'groupLeader' || key.roleKey == 'common') {
							this.isAllUser = true;
							break;
						}
					}
				} else {
					this.isAllUser = true;
				}
				//获取自己和同部门的用户信息
				getUserListData().then(response => {
					this.teamOptions = response.data;
				});

			},
			//转移客户
			transCustomer() {
				if (this.ids == '') {
					this.$message.error('请先选择用户');
					return false;
				}
				this.dialogFormVisible = true
			},
			// 转移客户提交
			submitForm() {
				let data = {
					ids: this.ids.join(','),
					businessManagerId: this.form.businessManagerId,
					remark: this.form.remark
				}
				console.log(data, 'data===')
				this.$refs["formRef"].validate(valid => {
					if (valid) {
						transferCustomer(data).then(response => {
							this.dialogFormVisible = false
							this.$modal.msgSuccess("转移成功");
							this.getList();
						})
					}
				})

			},
			// 点击切换页
			handleClick(tab, event) {
				this.index = tab.index
				if (this.index == 0) {
					// 我的客户
					this.queryParams.customerRoleType = 1 
				} else if(this.index == 1) {
					// 重点客户
					this.queryParams.customerRoleType = 3 
				}else{
					// 全部客户
					this.queryParams.customerRoleType = ''
				}
				this.getList()
			},
			getList() {
				this.getMyList()
				// this.queryParams.customerRoleType = 1 //1=我的客户 2=下属客户 3重点客户 4今日新增
				// if (this.index == 0) {
				// 	this.queryParams.customerRoleType = 1 
				// 	// 我的客户
				// 	this.getMyList()
				// } else {
				// 	this.queryParams.customerRoleType = 3 
				// 	// 重点客户
				// 	this.getMyList()
				// 	// this.getPointList()
				// }
			},
			// 客户详情
			handleDetail(url){
				this.$router.push(url)
			},
			// 跟进
			handleUser(row) {
				this.customerId = row.id
				this.$refs.dialog2.open()
			},
			// 请求我的客户列表数据
			getMyList() {
				this.loading = true;
				customerList(this.queryParams).then(response => {
					this.list = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			// 请求重点客户列表数据
			getPointList() {
				this.loading = true;
				favoriteCustomerList(this.queryParams).then(response => {
					this.list = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id);
				// single.value = selection.length != 1;
				// multiple.value = !selection.length;
			},
			// 搜索按钮操作
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			// 重置按钮操作
			resetQuery() {
				this.$refs.clearPicker.clearPickerValue()
				this.queryParams = {
					pageNum: 1,
					pageSize: 10,
					customerStatus: '', //客户状态
					customerType: '', //客户类型
					customerStarLevel: '', //客户星级
					startTime: '', //开始时间
					endTime: '', //结束时间					
					keyWords: '', //关键词
					customerRoleType: 1, //1=我的客户 2=下属客户 3重点客户 4今日新增
					recentlyConsumption: '', //最近消费1=一周内2=二周内3=一月内
					recentlyConsumptionNumber: '', //最近消费次数1=1次2=2次3=3次4=4次5=5次6=5次以上
					followUpStartTime: '', //下次跟进开始时间
					followUpEndTime: '', //下次跟进结束时间
					customerLabels: '', //客户标签
					businessManagerId: '', //业务经理
					createTimes: '',
					opportunitySource:'',//客户来源
				}
				this.handleQuery();
			},
			//时间
			changeTime(e) {
				this.queryParams.createTimes = e.join(',')
				// this.getList();
			},
			queryParamsFunc(e) {
				this.queryParams = e
				this.getList();
			},
			// 添加
			handleAdd() {
				this.$refs.customerPop.open('')
				// this.$router.push('/peoples/customer_add?id=' + 1)
			},
			//编辑
			handleEdit(row) {
				this.$refs.customerPop.open(row.id)
			},
			// 新建订单
			handleOrder(val) {
				this.addOrderCustomerMes = {
					customerId:val.id,
					customerName:val.customerName,//客户姓名
					opportunitySource:val.opportunitySource,//客户来源
					businessManagerId:val.businessManagerId,//业务经理id
					businessManagerName:val.businessManagerName,//业务经理名称
					phoneNumber:val.phoneNumber,
					shippingAddress:val.detailedAddress,
					localArea: val.localArea,
					localAreaName: val.localAreaName,
					localCity: val.localCity,
					localCityName: val.localCityName,
					localCounty:val.localCounty,
					localCountyName: val.localCountyName,
					localProvince:val.localProvince,
					localProvinceName: val.localProvinceName
				}
				console.log(this.addOrderCustomerMes,'addOrderCustomerMes')
				// this.addOrderCustomerId = row.id //要新建订单的客户id
				setTimeout(()=>{
					this.$refs.addOrder.open('')
				},200)
			}
		}
	}
</script>
<style>
	.el-checkbox {
		margin-bottom: 0 !important;
	}
</style> */